<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            placeholder="请输入内容"
            v-model="queryInfo.query"
            class="input-with-select"
            clearable
            @clear="getUsersList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUsersList"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addAeditClick('add')"
            >添加用户</el-button
          >
        </el-col>
      </el-row>
      <el-table :data="usersList" border stripe>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="userStatus(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" prop="mg_state" width="180px">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-edit"
              @click="addAeditClick('edit', scope.row)"
            ></el-button>
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
              @click="deleteitem(scope.row.id)"
            ></el-button>

            <el-tooltip
              class="item"
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                size="mini"
                type="warning"
                icon="el-icon-setting"
                @click="showRoleDialog(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <el-dialog
      :title="addAEditDialogTitle"
      :visible.sync="addAEditDialogVisible"
      width="50%"
      @close="addAEditDialogClose"
    >
      <el-form
        :model="addAEditForm"
        :rules="addAEditFormRules"
        ref="addFormRef"
        label-width="70px"
        class="demo-ruleForm"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="addAEditForm.username"
            :disabled="addAEditType === 'edit' ? true : false"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="密码"
          prop="password"
          type="password"
          v-if="addAEditType === 'add'"
        >
          <el-input v-model="addAEditForm.password" type="password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addAEditForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="addAEditForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addAEditDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addAEditCheckBtn">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="分配角色"
      :visible.sync="roleDialogVisible"
      width="50%"
      @close="roleDialogClose"
    >
      <p>当前的用户：{{ userInfo.username }}</p>
      <p>当前的角色：{{ userInfo.role_name }}</p>
      <p>
        分配新角色：
        <el-select v-model="selectName" placeholder="请选择">
          <el-option
            v-for="item in roleList"
            :key="item.id"
            :label="item.roleName"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </p>
      <span slot="footer" class="dialog-footer">
        <el-button @click="roleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="setRole">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data () {
    var checkEmail = (rule, value, cb) => {
      const refEmail = /^\w+@\w+\.\w+$/
      if (refEmail.test(value)) {
        return cb()
      }
      return cb(new Error('邮箱不符合验证规则'))
    }
    var checkMobile = (rule, value, cb) => {
      const refMobile = /^1(3|5|6|8|9)\d{9}$/
      if (refMobile.test(value)) {
        return cb()
      }
      return cb(new Error('电话不符合验证规则'))
    }
    return {
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      usersList: [],
      total: 0,
      addAEditDialogVisible: false,
      addAEditType: '',
      addAEditForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      addAEditFormRules: {
        username: [
          { required: true, message: '请输入用户名称', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      userInfo: {},
      roleDialogVisible: false,
      roleList: [],
      selectName: ''
    }
  },
  created () {
    this.getUsersList()
  },
  methods: {
    async getUsersList () {
      const { data: res } = await this.$http.get('users', { params: this.queryInfo })
      console.log(res)
      if (res.meta.status !== 200) return this.$message.error('获取用户列表失败！')
      this.usersList = res.data.users
      this.total = res.data.total
    },
    handleSizeChange (newPageSize) {
      this.queryInfo.pagesize = newPageSize
      this.getUsersList()
    },
    handleCurrentChange (newPageNum) {
      this.queryInfo.pagenum = newPageNum
      this.getUsersList()
    },
    async addAeditClick (type, row) {
      this.addAEditForm.username = ''
      this.addAEditForm.password = ''
      this.addAEditForm.email = ''
      this.addAEditForm.mobile = ''
      if (type === 'edit') {
        const { data: res } = await this.$http.get('users/' + row.id)
        if (res.meta.status !== 200) return this.$message.error(' 查询用户信息失败！')
        this.addAEditForm = res.data
      }
      this.addAEditDialogVisible = true
      this.addAEditType = type
    },
    addAEditCheckBtn () {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        if (this.addAEditType === 'add') {
          const { data: res } = await this.$http.post('users', this.addAEditForm)
          console.log(res)
          if (res.meta.status !== 201) return this.$message.error('添加用户失败！')
          this.$message.success('添加用户成功！')
          this.addAEditDialogVisible = false
          this.total = Math.ceil(this.total / this.queryInfo.pagesize) === this.total / this.queryInfo.pagesize ? this.total + 1 : this.total
          this.queryInfo.pagenum = Math.ceil(this.total / this.queryInfo.pagesize)
          this.getUsersList()
        } else if (this.addAEditType === 'edit') {
          console.log(this.addAEditForm)
          const { data: res } = await this.$http.put('users/' + this.addAEditForm.id, { email: this.addAEditForm.email, mobile: this.addAEditForm.mobile })
          if (res.meta.status !== 200) return this.$message.error('修改用户失败！')
          this.$message.success('修改用户成功！')
          this.addAEditDialogVisible = false
          this.getUsersList()
        }
      })
    },
    async userStatus (row) {
      const { data: res } = await this.$http.put(`users/${row.id}/state/${row.mg_state}`)
      if (res.meta.status !== 200) {
        row.mg_state = !row.mg_state
        this.$message.error('修改状态失败！')
        return
      }
      this.$message.success('修改状态成功！')
      this.getUsersList()
    },
    addAEditDialogClose () {
      this.$refs.addFormRef.resetFields()
    },
    async deleteitem (id) {
      const confirmResult = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmResult !== 'confirm') return this.$message('已取消删除！')
      const { data: res } = await this.$http.delete('users/' + id)
      if (res.meta.status !== 200) return this.$message.error('删除用户失败！')
      this.$message.success('删除用户成功！')
      if (this.usersList.length === 1 && this.queryInfo.pagenum > 1) {
        this.queryInfo.pagenum--
        this.getUsersList()
      }
      this.getUsersList()
    },
    async showRoleDialog (userInfo) {
      this.userInfo = userInfo
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.error('获取角色列表失败！')
      this.roleList = res.data
      console.log(this.roleList)
      this.roleDialogVisible = true
    },
    roleDialogClose () {
      this.selectName = ''
    },
    async setRole () {
      const { data: res } = await this.$http.put(`users/${this.userInfo.id}/role`, { rid: this.selectName })
      if (res.meta.status !== 200) return this.$message.error('分配用户角色失败！')
      this.$message.success('分配用户角色成功！')
      this.roleDialogVisible = false
      this.getUsersList()
    }
  },
  computed: {
    addAEditDialogTitle () {
      return this.addAEditType === 'add' ? '添加用户' : '修改用户'
    }
  }
}
</script>
<style scoped>
</style>
